package com.monitor.zk.zookeeper.command;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.SystemUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public abstract class AbstractExecCommand {

    /**
     * 系统命令
     */
    private static final List<String> COMMAND = new LinkedList<>();

    static {
        if (SystemUtil.getOsInfo().isLinux()) {
            //执行linux系统命令
            COMMAND.add("/bin/sh");
            COMMAND.add("-c");
        }
    }

    public String execCommand(String[] command) throws IOException {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            return RuntimeUtil.getResult(process);
        }finally {
            close(process);
        }
    }

    public static String execCommand(String command) {
        return execCommand(command,null);
    }
    /**
     * 在指定文件夹下执行命令
     *
     * @param command 命令
     * @param file    文件夹
     * @return msg
     */
    public static String execCommand(String command, File file) {
        String newCommand = StrUtil.replace(command, StrUtil.CRLF, StrUtil.SPACE);
        newCommand = StrUtil.replace(newCommand, StrUtil.LF, StrUtil.SPACE);
        String result = "error";
        try {
            List<String> commands = getCommand();
            commands.add(newCommand);
            String[] cmd = commands.toArray(new String[]{});
            result = exec(cmd, file);
        } catch (Exception e) {
            log.error("执行命令异常", e);
            result += e.getMessage();
        }
        return result;
    }

    /**
     * 执行命令
     *
     * @param cmd 命令行
     * @return 结果
     * @throws IOException IO
     */
    private static String exec(String[] cmd, File file) throws IOException {
        log.info("执行命令:{}",Arrays.toString(cmd));
        Process process = new ProcessBuilder(cmd).directory(file).redirectErrorStream(true).start();
        return RuntimeUtil.getResult(process);
    }

    public void close(Process process) throws IOException {
        if(process != null){
            process.getOutputStream().close();
            process.getInputStream().close();
            process.getErrorStream().close();
        }
    }

    public static List<String> getCommand() {
        return ObjectUtil.clone(COMMAND);
    }
}
